const socket = new WebSocket("ws://localhost:8080");
socket.addEventListener("open", function (event) {
    socket.send(JSON.stringify({
        type: "megadice_data"
    }));
});

socket.addEventListener("message", function (event) {
    let data = JSON.parse(event.data)
    if (data.type == "megadice_data") {
        queueUpdate(data.data);
    }
    if (data.type == "ps3838_data") {
        handlerPS3838(data.data)
    }
});

socket.addEventListener("close", function (event) {
})

let pendingUpdates = new Map();
let pendingUpdatesPS = new Map();

function queueUpdate(data) {
    for (let i = 0; i < data.length; i++) {
        let match = data[i]
        pendingUpdates.set(match.id, match);
    }
}

function applyUpdates() {
    pendingUpdates.forEach((match, matchId) => {
        updateMatch(matchId, match);
    });
    pendingUpdatesPS.forEach((match, matchId) => {
        updatePS(matchId, match);
    });
    pendingUpdates.clear();
    pendingUpdatesPS.clear();
    requestAnimationFrame(applyUpdates);
}


function updateMatch(matchId, match) {
    const matchElement = document.getElementById(`${matchId}`);
    const container = document.getElementById("match-list");
    if (!matchElement) {
        // 创建比赛
        let el = createMatch(match)
        container.appendChild(el)
        return
    } else {
        if (match.time) {
            document.getElementById(`${match.id}_time`).textContent = match.time
        }
        if (match.score) {
            document.getElementById(`${match.id}_score`).textContent = match.score
        }
        if (match.handap) {
            let handapEl = match.handap?.slice(0, 3).map(h => {
                let odd1 = false
                let odd2 = false
                if (PS3838_DATA.has(matchId)) {
                    let psMatch = PS3838_DATA.get(matchId)
                    for (let i = 0; psMatch.handap && i < psMatch.handap.length; i++) {
                        let item = psMatch.handap[i]
                        if (item.v == h.v) {
                            odd1 = item.a
                            odd2 = item.b
                        }
                    }
                }
                return `
                    <div class="handicap-row">
                       <span>${h.v}</span>
                       <span class="odds-cell">
                           <span class="odds-item">${h.a}</span> / <span class="odds-item secondary" id="ps-a-hp-${matchId}${h.v}"> ${odd1 ? odd1 : ""} </span>
                       </span>
                       <span class="odds-cell">
                           <span class="odds-item">${h.b}</span> / <span class="odds-item secondary" id="ps-b-hp-${matchId}${h.v}"> ${odd2 ? odd2 : ""} </span>
                       </span>
                   </div>
               `
            }).join('')
            document.getElementById(`${match.id}_handap`).innerHTML = handapEl;
        }
        if (match.over_under) {
            let ouEl = match.over_under?.slice(0, 3).map(h => {
                let odd1 = false
                let odd2 = false
                let redA = false
                let redB = false
                if (PS3838_DATA.has(matchId)) {
                    let psMatch = PS3838_DATA.get(matchId)
                    for (let i = 0; psMatch.over_under && i < psMatch.over_under.length; i++) {
                        let item = psMatch.over_under[i]
                        if (item.v == h.v) {
                            odd1 = item.a
                            odd2 = item.b
                            let oddA = powerDevig([parseFloat(odd1), parseFloat(odd2)], k = 0.95)
                            if (oddA[0] < parseFloat(h.a)) {
                                console.info(`发现价值投注1 >> ${odd1} | ` + oddA[0])
                                redA = true
                                odd1 = odd1 + ` > ${oddA[0]}`
                            }
                            if (oddA[1] < parseFloat(h.b)) {
                                console.info(`发现价值投注2 >> ${odd2} | ` + oddA[1])
                                redB = true
                                odd2 = odd2 + ` > ${oddA[1]}`
                            }
                        }
                    }
                }
                return `
                <div class="handicap-row">
                    <span>${h.v}</span>
                    <span class="odds-cell">
                        <span class="odds-item" style="${redA ? "color: gold;" : ""}">${h.a}</span> / <span class="odds-item secondary" id="ps-a-ou-${matchId}${h.v}"> ${odd1 ? odd1 : ""}  </span>
                    </span>
                    <span class="odds-cell">
                        <span class="odds-item" style="${redB ? "color: gold;" : ""}">${h.b}</span> / <span class="odds-item secondary" id="ps-b-ou-${matchId}${h.v}">  ${odd2 ? odd2 : ""} </span>
                    </span>
                </div>
            `
            }).join('')
            document.getElementById(`${match.id}_ou`).innerHTML = ouEl;
        }
    }

}


function createMatch(match) {
    const matchEl = document.createElement("div");
    matchEl.className = "match-item";
    matchEl.id = match.id; // 用于后续更新
    let id = match.id
    let handapEl = match.handap?.slice(0, 3).map(h => {
        let odd1 = false
        let odd2 = false
        if (PS3838_DATA.has(id)) {
            let psMatch = PS3838_DATA.get(id)
            for (let i = 0; psMatch.handap && i < psMatch.handap.length; i++) {
                let item = psMatch.handap[i]
                if (item.v == h.v) {
                    odd1 = item.a
                    odd2 = item.b
                }
            }
        }
        return `
            <div class="handicap-row">
               <span>${h.v}</span>
               <span class="odds-cell">
                   <span class="odds-item">${h.a}</span> / <span class="odds-item secondary" id="ps-a-hp-${id}${h.v}"> ${odd1 ? odd1 : ""} </span>
               </span>
               <span class="odds-cell">
                   <span class="odds-item">${h.b}</span> / <span class="odds-item secondary" id="ps-b-hp-${id}${h.v}"> ${odd2 ? odd2 : ""} </span>
               </span>
           </div>
       `
    }).join('')
    let ouEl = match.over_under?.slice(0, 3).map(h => {
        let odd1 = false
        let odd2 = false
        let redA = false
        let redB = false
        if (PS3838_DATA.has(id)) {
            let psMatch = PS3838_DATA.get(id)
            for (let i = 0; psMatch.over_under && i < psMatch.over_under.length; i++) {
                let item = psMatch.over_under[i]
                if (item.v == h.v) {
                    odd1 = item.a
                    odd2 = item.b
                    let oddA = powerDevig([parseFloat(odd1), parseFloat(odd2)], k = 0.95)
                    if (oddA[0] < parseFloat(h.a)) {
                        console.info(`发现价值投注1 >> ${odd1} | ` + oddA[0])
                        redA = true
                        odd1 = odd1 + ` > ${oddA[0]}`
                    }
                    if (oddA[1] < parseFloat(h.b)) {
                        console.info(`发现价值投注2 >> ${odd2} | ` + oddA[1])
                        redB = true
                        odd2 = odd2 + ` > ${oddA[1]}`
                    }
                }
            }
        }
        return `
        <div class="handicap-row">
            <span>${h.v}</span>
            <span class="odds-cell">
                <span class="odds-item" style="${redA ? "color: gold;" : ""}" >${h.a}</span> / <span class="odds-item secondary" id="ps-a-ou-${id}${h.v}"> ${odd1 ? odd1 : ""}  </span>
            </span>
            <span class="odds-cell">
                <span class="odds-item" style="${redB ? "color: gold;" : ""}">${h.b}</span> / <span class="odds-item secondary" id="ps-b-ou-${id}${h.v}">  ${odd2 ? odd2 : ""} </span>
            </span>
        </div>
    `
    }).join('')
    matchEl.innerHTML = ` 
            <div class="time-score">
                <div class="time" id="${id}_time">${match.time}</div>
                <div class="score" id="${id}_score">${match.score}</div>
            </div>

            <div class="league" id="${id}_league">${match.league}</div>

            <div class="teams">
                <div class="team home" id="${id}_home">${match.home}</div>
                <div class="team away" id="${id}_away">${match.away}</div>
            </div>

            <!-- 让球盘口 -->
            <div>
                <div class="handicap-label">让球</div>
                <div class="handicap-group" id="${id}_handap">
                ${handapEl ? handapEl : ""}  
                </div>
            </div>
            <!-- 大小球盘口 -->
            <div>
                <div class="overunder-label">大小球</div>
                <div class="handicap-group" id="${id}_ou">
                ${ouEl ? ouEl : ""}  
                </div>
            </div> 
           
    `;

    return matchEl;
}

var PS3838_DATA = new Map()

function handlerPS3838(data) {
    for (let i = 0; i < data.length; i++) {
        let match = data[i]
        if (match.megadiceId) {
            PS3838_DATA.set(match.megadiceId, match)
            pendingUpdatesPS.set(match.megadiceId, match);
        }
    }
}

function updatePS(matchId, match) {
    if (match.over_under) {
        for (let i = 0; i < match.over_under.length; i++) {
            let item = match.over_under[i]
            let el1 = document.getElementById(`ps-a-ou-${matchId}${item.v}`)
            let el2 = document.getElementById(`ps-b-ou-${matchId}${item.v}`)
            if (el1) {
                el1.textContent = item.a
            }
            if (el2) {
                el2.textContent = item.b
            }
        }
    }

    if (match.handap) {
        for (let i = 0; i < match.handap.length; i++) {
            let item = match.handap[i]
            let el1 = document.getElementById(`ps-a-hp-${matchId}${item.v}`)
            let el2 = document.getElementById(`ps-b-hp-${matchId}${item.v}`)
            if (el1) {
                el1.textContent = item.a
            }
            if (el2) {
                el2.textContent = item.b
            }
        }
    }
}

function decimalOddsToProbabilities(odds) {
    return odds.map(o => 1 / o);
}

function powerDevig(odds, k = 0.95) {
    const impliedProbs = decimalOddsToProbabilities(odds);

    // 计算分母：所有概率的 k 次幂总和
    const denominator = impliedProbs.reduce((sum, p) => sum + Math.pow(p, k), 0);

    // 归一化后的概率
    const devigProbs = impliedProbs.map(p => Math.pow(p, k) / denominator);

    // 转换为 no-vig 小数赔率
    const devigOdds = devigProbs.map(p => 1 / p);

    return devigOdds;
}

requestAnimationFrame(applyUpdates);